package com.stephen.redisdemo.atomic;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author: stephen
 * @create: 2020-02-29 14:43
 * @description: 信号量
 * 信号量这个东西可以循环使用
 * 就像10辆车抢3个车位,只要前边的车离开,后边的车就可以继续抢占
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                try {
                    // 获取信号量
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t" + "抢到车位");
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放信号量
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "\t" + "离开车位");
                }
            },String.valueOf(i)).start();
        }
    }
}
